package com.shaoshaohuo.app.ui.ec;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.db.DaoUtils;
import com.shaoshaohuo.app.entity.EcCategoryFirst;
import com.shaoshaohuo.app.entity.EcCategorySecond;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.adapter.ProductTypeFirstListAdapter;
import com.shaoshaohuo.app.adapter.ProductTypeSecondListAdapter;
import com.shaoshaohuo.app.view.HanziToPingyin;
import com.shaoshaohuo.app.view.LetterView;
import com.shaoshaohuo.app.view.LetterView.OnTouchingLetterChangedListener;
import com.shaoshaohuo.app.view.TopbarView;

/**
 * @ClassName ProductTypeActivity
 * @author linmu
 * @Decription 商品分类
 * @2015-8-28 下午10:12:24
 */
public class ProductTypeActivity extends BaseActivity implements OnClickListener {

	private TopbarView mTopbarView;

	private View mSearchLayout;
	private EditText mSearchEdit;

	private TextView mLeftTabText;
	private TextView mRightTabText;

	private ListView mFirstListview;
	private ListView mSecondListview;

	private Handler mHandler = new Handler();
	private LetterView letterView;
	private HashMap<String, Integer> alphaIndexer;
	private OverlayThread mOverlayThread;
	private WindowManager mWindowManager;
	private TextView mOverlay;
	protected List<EcCategorySecond> query;

    private List<EcCategoryFirst> firstTypeList;

    private String currentCatid;

    private ProductTypeFirstListAdapter<Object> firstTypeAdapter;

    private boolean isSelectStatus = false;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_type);
		initData();
		initView();
		initOverlay();
		setUpView();
	}

	private void initData() {
		isSelectStatus = getIntent().getBooleanExtra(ExtraName.action, false);
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mSearchLayout = this.findViewById(R.id.layout_search);
		mSearchEdit = (EditText) this.findViewById(R.id.edittext_search);

		mLeftTabText = (TextView) this.findViewById(R.id.textview_tab_left);
		mRightTabText = (TextView) this.findViewById(R.id.textview_tab_right);

		mFirstListview = (ListView) this.findViewById(R.id.listview_type_list_first);
		mSecondListview = (ListView) this.findViewById(R.id.listview_type_list_second);
		
		initLetterView();
	}

	private void setUpView() {
		mTopbarView.setCenterText("分类");
		mTopbarView.setLeftView(true, true);

		mLeftTabText.setOnClickListener(this);
		mRightTabText.setOnClickListener(this);
		mLeftTabText.setSelected(true);
		mRightTabText.setSelected(false);

		setFirstList();
		
		mFirstListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EcCategoryFirst first = (EcCategoryFirst) parent.getItemAtPosition(position);
                getSecondData(first.getCatid());
                firstTypeAdapter.setSelectPosition(position);
            }
        });
		
		mSecondListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EcCategorySecond item = (EcCategorySecond) parent.getItemAtPosition(position);
                if(!item.isTitle()){
                    Intent intent = new Intent();
                    intent.putExtra(ExtraName.ecCategorySecond, item);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
	}

	private void setFirstList() {
		firstTypeList = DaoUtils.findAllEcCategoryFirst();

		if(firstTypeAdapter == null){
		    firstTypeAdapter = new ProductTypeFirstListAdapter<>(this, firstTypeList, false);
		    mFirstListview.setAdapter(firstTypeAdapter);
		}

		if(firstTypeList!=null && !firstTypeList.isEmpty()){
		    getSecondData(firstTypeList.get(0).getCatid());
		}
		// setSecondList();
	}

	private void getSecondData(String catid) {
	    if(catid.equals(currentCatid)){
	        return;
	    }
	    this.currentCatid = catid;
		List<EcCategorySecond> list = DaoUtils.findAllEcCategorySecond(catid);
		if(list!=null && !list.isEmpty()){
		    initSecondTypeData(list);
		}else{
		    setSecondList(list);
		}
	}

	private void setSecondList(List<EcCategorySecond> query2) {
	    
		ProductTypeSecondListAdapter<EcCategorySecond> adapter = new ProductTypeSecondListAdapter<>(this, query2, false);
		mSecondListview.setAdapter(adapter);
	}

	private void initLetterView() {
		letterView = (LetterView) findViewById(R.id.letterview);
		letterView.setOnTouchingLetterChangedListener(new letterViewListener());
		alphaIndexer = new HashMap<String, Integer>();
		mOverlayThread = new OverlayThread();
	}
	
	private void initSecondTypeData(final List<EcCategorySecond> list) {
		startLoadingDialog();
		new Thread() {
			public void run() {
				query = sortContactTitle(list);

				if(!isSelectStatus){
					EcCategorySecond s = new EcCategorySecond();
					s.setCatname("不限");
					query.add(0,s);
				}
				
				alphaIndexer.clear();
				for (int i = 0; i < query.size(); i++) {
					EcCategorySecond entity = query.get(i);
					if (entity.isTitle) {
						alphaIndexer.put(entity.title, i);
					}
				}

				mHandler.post(new Runnable() {

					@Override
					public void run() {
						dismissLoadingDialog();
						setSecondList(query);
					}

				});
			};
		}.start();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.textview_tab_left:
			if (mLeftTabText.isSelected()) {
				return;
			}
			mLeftTabText.setSelected(true);
			mRightTabText.setSelected(false);

			// addBuyersLayout();
			break;
		case R.id.textview_tab_right:
			if (mRightTabText.isSelected()) {
				return;
			}
			mLeftTabText.setSelected(false);
			mRightTabText.setSelected(true);

			// addSellersLayout();

			break;
		}
	}

	private void initOverlay() {
		mHandler = new Handler();
		LayoutInflater inflater = LayoutInflater.from(this);
		mOverlay = (TextView) inflater.inflate(R.layout.contacts_overlay, null);
		mOverlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, PixelFormat.TRANSLUCENT);
		mWindowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
		mWindowManager.addView(mOverlay, lp);
	}

	@Override
	protected void onDestroy() {
		if (mWindowManager != null) {
			mWindowManager.removeView(mOverlay);
			mWindowManager = null;
		}
		super.onDestroy();
	}

	@Override
	public void finish() {
		try {
			if (mWindowManager != null) {
				mWindowManager.removeView(mOverlay);
				mWindowManager = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.finish();
	}

	private class OverlayThread implements Runnable {
		@Override
		public void run() {
			mOverlay.setVisibility(View.GONE);
		}
	}

	private class letterViewListener implements OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(final String s) {
			if (alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s);
				mSecondListview.setSelection(position);
				mOverlay.setText(s);
				mOverlay.setVisibility(View.VISIBLE);
				mHandler.removeCallbacks(mOverlayThread);
				mHandler.postDelayed(mOverlayThread, 1500);
			}
		}

	}

	public static List<EcCategorySecond> sortContactTitle(List<EcCategorySecond> data) {
		if (data == null) {
			return null;
		}

		for (EcCategorySecond userInfoEntity : data) {
			if (TextUtils.isEmpty(userInfoEntity.getPinyin())) {
				String name = userInfoEntity.getCatname();
				String pinyin = HanziToPingyin.getPinYin(name);
				pinyin = TextUtils.isEmpty(pinyin) ? "~" : pinyin;
				userInfoEntity.setPinyin(pinyin);
			}
		}

		System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
		Collections.sort(data, new Comparator<EcCategorySecond>() {
			@Override
			public int compare(EcCategorySecond lhs, EcCategorySecond rhs) {

				int lhsascll = lhs.getPinyin().charAt(0);
				int rhsascll = rhs.getPinyin().charAt(0);

				if (lhsascll < 97 || lhsascll > 122) {
					lhs.setPinyin("~");
				}

				if (rhsascll < 97 || rhsascll > 122) {
					rhs.setPinyin("~");
				}

				return lhs.getPinyin().compareTo(rhs.getPinyin());
			}
		});

		char mc = '*';
		List<EcCategorySecond> newData = new ArrayList<EcCategorySecond>();
		for (int i = 0; i < data.size(); i++) {
			EcCategorySecond friend = data.get(i);
			friend.setTitle(false);
			char c = HanziToPingyin.getFirstPinYinChar(friend.getPinyin());
			// char c = HanziToPingyin
			// .getFirstPinYinChar(TextUtils.isEmpty(friend.getFriendMark().getRemarkName())
			// ? friend.getName()
			// : friend.getFriendMark().getRemarkName());

			if (c < 65 || c > 90) {
				c = '#';
			}

			if (mc != c) {
				mc = c;
				EcCategorySecond f = new EcCategorySecond();
				f.setTitle(true);
				f.setTitle(String.valueOf(c));
				newData.add(f);
			}
			newData.add(friend);
		}
		return newData;
	}

}
